package com.example.springbootsecurityjwt.filter;

import com.example.springbootsecurityjwt.domain.LoginUser;
import com.example.springbootsecurityjwt.utils.JwtUtil;
import com.example.springbootsecurityjwt.utils.RedisCache;
import io.jsonwebtoken.Claims;
import io.netty.util.internal.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @program: SpringBoot-Security-JWT
 * @description: JWT认证过滤器
 * @author: Coder_Pan
 * @create: 2022-03-22 14:11
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final RedisCache redisCache;

    public JwtAuthenticationTokenFilter(RedisCache redisCache) {
        this.redisCache = redisCache;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = httpServletRequest.getHeader("token");
        //Token不存在时放行
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            //放行后return就不进行后续的解析操作
            return;
        }
        //当token不为空  ==》  解析token
        String userId;//扩大作用域
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("Token非法");
        }
        //从redis中获取用户信息  ==》 Token合法
        String redisKey = "login:" + userId;
        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        if (Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        /**
         * TODO 权限信息 =》authorities
         * 权限信息通过loginUser.getAuthorities()获取
         */
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());//在已认证的状态下，直接传入loginUser，null，权限信息

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //最后解析结束
        //通过filterChain.doFilter(httpServletRequest,httpServletResponse)放行
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
